package com.lindroy.androidplayer.ui.coin

import android.annotation.SuppressLint
import androidx.activity.viewModels
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseActivity
import com.lindroy.androidplayer.extensions.*
import com.lindroy.androidplayer.logic.model.CoinHistoryResp
import com.lindroy.androidplayer.viewmodel.CoinViewModel
import com.lindroy.lib_utils.extensions.setGone
import com.lindroy.lib_utils.extensions.setVisible
import com.youngfeng.snake.annotations.EnableDragToClose
import kotlinx.android.synthetic.main.activity_coin_history.*
import java.text.SimpleDateFormat
import java.util.*


/**
 * @author Lin
 * @date 2021/4/26
 * @function 积分记录
 * @Description
 */

@EnableDragToClose
class CoinHistoryActivity(override val layoutId: Int = R.layout.activity_coin_history) :
    BaseActivity() {

    private val coinViewModel: CoinViewModel by viewModels()

    private val adapter: BaseSimpleAdapter<CoinHistoryResp> by lazy {
        BaseSimpleAdapter<CoinHistoryResp>(R.layout.coin_history_item) { holder, item ->
            @SuppressLint("SimpleDateFormat")
            fun timeMillsToDate(timeMills: Long) =
                SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(timeMills))
            val coinDetail = item.desc.substringAfterLast("：").trim()
                holder.setText(R.id.tvCoin, "+${item.coinCount}")
                    .setText(R.id.tvDate,timeMillsToDate(item.date))
                    .setText(R.id.tvCoinDetail,"${item.reason}:$coinDetail")
        }
    }

    override fun initView() {
        initToolBar(R.string.nav_my_score)
        refreshHeader.initColor()
        rvCoinHistory.setLineDivider()
        rvCoinHistory.adapter = adapter
        //Todo（总数字可以增加一个数字变动动画）
        tvCoinSum.text = globalLoginInfo.coinCount.toString()
    }

    override fun initData() {
        reqCoinHistory(true)
    }

    override fun initListener() {
        coinViewModel.coinHistoryState.observe(this) {
            loadListData(it, adapter, refreshLayout, stateLayout)
            it.success.yes { flContent.setVisible() }.no { flContent.setGone() }
        }
        refreshLayout.setOnRefreshListener { reqCoinHistory(false) }
        refreshLayout.setOnLoadMoreListener { reqCoinHistory(false, false) }
        stateLayout.setOnViewsClickListener { state, view ->
            reqCoinHistory(true)
        }
    }

    private fun reqCoinHistory(showLoading: Boolean, isRefresh: Boolean = true) {
        if (showLoading) {
            stateLayout.showLoading()
        }
        coinViewModel.reqCoinHistory(isRefresh)
    }

    override fun initClick() {

    }
}